package cn.dida.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import cn.dida.exception.BizzException;
import cn.dida.model.HttpResponseBodyWrapper;
import cn.dida.model.Pageable;
import cn.dida.model.UserSession;
import cn.dida.service.QrcodeAutoProductService;
import cn.dida.util.DateUtils;
import cn.dida.util.ExcelUtil;

@Controller
public class QrcodeAutoProductController extends BaseController{
	
	@Autowired
	private QrcodeAutoProductService qrcodeAutoProductService;
	
	/**
	 * 自动绑定列表查询
	 * @author kelan
	 * @date 2018年1月22日
	 * @param request
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/qrcodeautoproduct")
	public ModelAndView QrcodeAutoProduct_List(HttpServletRequest request, Integer page) throws Exception {
		Map<String, Object> model = new HashMap<String, Object>();
		UserSession userSession = getUserSession(request);
		Map<String, Object> paramMap = getSimpleRequestParamMap(request);
		page = (page == null || page < 1) ? 1 : page;
		Pageable<Map<String, Object>> pagelist = qrcodeAutoProductService.queryLgsQrcodeExtendList(userSession.getCompanyId(),
				paramMap, page);
		pagelist.setRquesturl(request, paramMap);
		model.put("pagelist", pagelist);
		for (String key : paramMap.keySet()) {
			model.put(key, paramMap.get(key));
		}

		return new ModelAndView("qrcode_auto_product_list").addAllObjects(model);
	}

	
	/**
	 * 自动绑定明细查询
	 * @author kelan
	 * @date 2018年1月22日
	 * @param request
	 * @param prodBillcode
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/qrcodeautoproduct/detail")
	public ModelAndView QrcodeAutoProduct_detail_List(HttpServletRequest request,String  prodBillcode, Integer page) throws Exception {
		Map<String, Object> model = new HashMap<String, Object>();
		UserSession userSession = getUserSession(request);
		Map<String, Object> paramMap = getSimpleRequestParamMap(request);
		page = (page == null || page < 1) ? 1 : page;
		Pageable<Map<String, Object>> pagelist = qrcodeAutoProductService.queryLgsQrcodeExtendDetail(userSession.getCompanyId(),
				prodBillcode,paramMap, page);
		pagelist.setRquesturl(request, paramMap);
		model.put("pagelist", pagelist);
		model.put("prodBillcode", prodBillcode);
		for (String key : paramMap.keySet()) {
			model.put(key, paramMap.get(key));
		}
		return new ModelAndView("qrcode_auto_product_detail").addAllObjects(model);
	}
	
	
	/**
	 * 自动绑定列表 数据导出
	 * @author kelan
	 * @date 2018年1月22日
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@GetMapping("/qrcodeautoproduct/export")
    public String qrcode_product_export(HttpServletRequest request,HttpServletResponse response) throws IOException{
    	
    	UserSession userSession = getUserSession(request);
    	Map<String, Object> paramMap = getSimpleRequestParamMap(request);
    	
		List<Map<String, Object>> exportList = qrcodeAutoProductService.queryLgsQrcodeExtendListNopage(userSession.getCompanyId(), paramMap);
		
    	String fileName="自动绑定数据导出"+DateUtils.dateToString(Calendar.getInstance().getTime(), "yyyy-MM-dd");
    	String columnNames[] = {"生产单据号","产品","产品编码","箱数","是否营销","生成时间","灌装厂编码"};//列名
    	String keys[] = {"prodBillcode","proname","procode","billNumber","is_act","prod_date","prod_fillingplantcode"};//map中的key
    	ByteArrayOutputStream os = new ByteArrayOutputStream();
    	try {
    		ExcelUtil.createWorkBook(exportList,keys,columnNames).write(os);
    	} catch (IOException e) {
    		e.printStackTrace();
    	}
    	byte[] content = os.toByteArray();
    	InputStream is = new ByteArrayInputStream(content);
    	// 设置response参数，可以打开下载页面
    	response.reset();
    	response.setContentType("application/vnd.ms-excel;charset=utf-8");
    	response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
    	ServletOutputStream out = response.getOutputStream();
    	BufferedInputStream bis = null;
    	BufferedOutputStream bos = null;
    	try {
    		bis = new BufferedInputStream(is);
    		bos = new BufferedOutputStream(out);
    		byte[] buff = new byte[2048];
    		int bytesRead;
    		// Simple read/write loop.
    		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
    			bos.write(buff, 0, bytesRead);
    			bos.flush();
    		}
    	} catch (final IOException e) {
    		throw e;
    	} finally {
    		if (bis != null)
    			bis.close();
    		if (bos != null)
    			bos.close();
    	}
    	
    	return null;
    }
	
	/**
	 * 自动绑定明细数据导出
	 * @author kelan
	 * @date 2018年1月22日
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@GetMapping("/qrcodeautoproductdetail/export")
    public String qrcode_product_detail_export(HttpServletRequest request,HttpServletResponse response) throws IOException{
    	
    	UserSession userSession = getUserSession(request);
    	Map<String, Object> paramMap = getSimpleRequestParamMap(request);
    	
		List<Map<String, Object>> exportList = qrcodeAutoProductService.queryLgsQrcodeExtendDetailNopage(userSession.getCompanyId(), paramMap);
		
    	String fileName="自动绑定数据导出"+DateUtils.dateToString(Calendar.getInstance().getTime(), "yyyy-MM-dd");
    	String columnNames[] = {"产品","产品批次号","班组编号","小箱码","箱码编号","瓶码编号","上传时间"};//列名
    	String keys[] = {"proname","prodBatchno","prod_groupcode","innerBox","outerboxId","qrcodeId","ctime"};//map中的key
    	ByteArrayOutputStream os = new ByteArrayOutputStream();
    	try {
    		ExcelUtil.createWorkBook(exportList,keys,columnNames).write(os);
    	} catch (IOException e) {
    		e.printStackTrace();
    	}
    	byte[] content = os.toByteArray();
    	InputStream is = new ByteArrayInputStream(content);
    	// 设置response参数，可以打开下载页面
    	response.reset();
    	response.setContentType("application/vnd.ms-excel;charset=utf-8");
    	response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
    	ServletOutputStream out = response.getOutputStream();
    	BufferedInputStream bis = null;
    	BufferedOutputStream bos = null;
    	try {
    		bis = new BufferedInputStream(is);
    		bos = new BufferedOutputStream(out);
    		byte[] buff = new byte[2048];
    		int bytesRead;
    		// Simple read/write loop.
    		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
    			bos.write(buff, 0, bytesRead);
    			bos.flush();
    		}
    	} catch (final IOException e) {
    		throw e;
    	} finally {
    		if (bis != null)
    			bis.close();
    		if (bos != null)
    			bos.close();
    	}
    	
    	return null;
    }
	
	@ResponseBody
	@PostMapping("/qrcodeautoproduct/upact")
	public HttpResponseBodyWrapper qrcode_product_upact_post(HttpServletRequest request, String prod_date, Integer type,String prodBillcode)
			throws Exception {

		if (prodBillcode == null) {
			throw new BizzException(BizzException.error_code_invalid_params, "生产单据号不能为空！");
		}
		if (type != 0 && type != 1) {
			throw new BizzException(BizzException.error_code_invalid_params, "营销状态有误！");
		}
		if (prod_date == null || prod_date.length()<=0){
			throw new BizzException(BizzException.error_code_invalid_params, "生产时间不能为空！");
		}
		UserSession userSession = getUserSession(request);
		Integer result = null;
	    result = qrcodeAutoProductService.updateQrcodeProductActSta(prod_date,prodBillcode, userSession, type);
		return new HttpResponseBodyWrapper(result);
	}
	
}
